import sys,os
sys.path.append(os.pardir)
import numpy as np 
from collections import OrderedDict
from common.layers import Affine,Relu,SoftmaxWithLoss
from common.gradient import numerical_gradient

class TwoLayerNet:
    def __init__(self,input_size,hidden_size,output_size,weight_init_std=0.01):
        # 初始化权重
        self.params = {}
        self.params['W1'] = weight_init_std*np.random.randn(input_size,hidden_size)
        self.params['b1'] = np.zeros(hidden_size)
        self.params['W2'] = weight_init_std*np.random.randn(hidden_size,output_size)
        self.params['b2'] = np.zeros(output_size)

        # 生成层 "affine1+relu || affine2+softmax"
        self.layers = OrderedDict()
        self.layers['Affine1'] = Affine(self.params['W1'],self.params['b1'])
        self.layers['Relu1'] = Relu()
        self.layers['Affine2'] = Affine(self.params['W2'],self.params['b2'])

        self.lastLayer = SoftmaxWithLoss()

    def predict(self,x):
        # 前向计算无需使用softmax
        for layer in self.layers.values():
            x = layer.forward(x)
        return x 
    
    def loss(self,x,t):
        # 返回网络的交叉熵损失，所以必须计算softmax层
        y = self.predict(x)
        return self.lastLayer.forward(y,t)
    
    def accuracy(self,x,t):
        '''计算一批训练数据的准确度'''
        y = self.predict(x)
        y = np.argmax(y,axis=1)
        if t.ndim != 1:
            t = np.argmax(t,axis=1)
        acc = np.sum(y==t)/float(x.shape[0])
        return acc 
    
    def numerical_gradient(self,x,t):
        '''数值微分计算梯度   
        '''
        loss_W = lambda W:self.loss(x,t)

        grads={}
        grads['W1'] = numerical_gradient(loss_W,self.params['W1'])
        grads['b1'] = numerical_gradient(loss_W,self.params['b1'])
        grads['W2'] = numerical_gradient(loss_W,self.params['W2'])
        grads['b2'] = numerical_gradient(loss_W,self.params['b2'])

        return grads
    
    def gradient(self,x,t):
        # forward
        self.loss(x,t)
        
        # backward
        dout = 1
        dout = self.lastLayer.backward(dout)

        layers = list(self.layers.values())
        layers.reverse()
        for layer in layers:
            dout = layer.backward(dout)

        # 设定
        grads = {}
        grads['W1'],grads['b1'] = self.layers['Affine1'].dW,self.layers['Affine1'].db
        grads['W2'],grads['b2'] = self.layers['Affine2'].dW,self.layers['Affine2'].db

        return grads 
